<template>
  <div class="app-container">
    <el-container>
      <el-header>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-input
              v-model="kwInput"
              placeholder="搜索名人名字或风格描述"
              class="input-with-select"
              clearable
              @keyup.native.enter="handleSearch"
            >
              <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </el-input>
          </el-col>
          <el-col :span="12">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="handleAction('create', '新增写作风格')"
            >新增写作风格
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              :disabled="!selectedRows.length"
              @click="handleBatchDelete"
            >批量删除
            </el-button>
          </el-col>
        </el-row>
      </el-header>
      <el-container>
        <el-main>
          <el-table
            v-loading.body="listLoading"
            :data="data"
            border
            fit
            highlight-current-row
            :default-sort="{prop: 'create_at', order: 'descending'}"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            @sort-change="handleSort"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column align="center" label="ID" width="80" prop="id" />
            <el-table-column align="center" label="名人名字" prop="celebrity_name" sortable="custom" />
            <el-table-column align="center" label="风格描述" prop="style_description" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.style_description }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.remark || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="创建者" prop="owner_name" width="120" />
            <el-table-column align="center" label="创建时间" prop="create_at" sortable="custom" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.create_at, '{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" fixed="right" width="280">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="handleAction('edit', scope.row)"
                >编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleAction('delete', scope.row)"
                >删除
                </el-button>
                <el-button
                  size="mini"
                  icon="el-icon-magic-stick"
                  style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                  @click="handleAITask(scope.row)"
                >AI改写
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="total > 0"
            background
            class="mt-pagination"
            :current-page="page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </el-main>
      </el-container>
    </el-container>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="60%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="dataForm" :model="temp" :rules="rules" label-position="left" label-width="120px">
        <el-form-item label="名人名字" prop="celebrity_name">
          <el-input
            v-model="temp.celebrity_name"
            placeholder="请输入名人名字，如：Seth Godin、海明威、村上春树等"
            @blur="onCelebrityNameBlur"
          />
        </el-form-item>
        <el-form-item label="风格描述" prop="style_description">
          <div class="style-description-container">
            <el-input
              v-model="temp.style_description"
              type="textarea"
              :rows="8"
              placeholder="请输入AI改写指令，告诉AI如何模仿该名人的写作风格（如：请模仿鲁迅的风格：使用犀利讽刺手法，短句为主...）"
            />
            <div class="style-helper-buttons">
              <el-button
                size="small"
                icon="el-icon-magic-stick"
                style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                :loading="generatingStyle"
                :disabled="!temp.celebrity_name"
                @click="generateStyleDescription"
              >
                AI生成风格描述
              </el-button>
              <el-button
                size="small"
                type="info"
                icon="el-icon-document"
                @click="showStyleExamples"
              >
                查看示例
              </el-button>
              <el-button
                size="small"
                icon="el-icon-edit"
                style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                :disabled="!temp.style_description"
                @click="optimizeStyleDescription"
              >
                优化描述
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="temp.remark"
            type="textarea"
            :rows="3"
            placeholder="选填：添加备注信息"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete' ? 'primary' : 'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- AI改写对话框 -->
    <el-dialog
      title="AI内容改写"
      :visible.sync="aiDialogVisible"
      width="80%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="ai-section">
            <h3 class="ai-section-title">原始内容</h3>
            <el-input
              v-model="aiTask.originalContent"
              type="textarea"
              :rows="15"
              placeholder="请输入需要改写的原始内容"
            />
            <div class="ai-section-footer">
              <el-button
                icon="el-icon-refresh-right"
                style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                :loading="aiTask.loading"
                @click="executeAIRewrite"
              >执行AI改写</el-button>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="ai-section">
            <h3 class="ai-section-title">改写结果</h3>
            <el-input
              v-model="aiTask.rewrittenContent"
              type="textarea"
              :rows="15"
              placeholder="改写结果将显示在这里"
              readonly
            />
            <div class="ai-section-footer">
              <el-button
                v-if="aiTask.rewrittenContent"
                type="success"
                icon="el-icon-document-copy"
                @click="copyRewrittenContent"
              >复制结果</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
      <div class="ai-style-info">
        <el-alert
          :title="`当前使用风格：${aiTask.currentStyle.celebrity_name}`"
          type="info"
          :description="aiTask.currentStyle.style_description"
          show-icon
          :closable="false"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="aiDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, BatchDelete } from '@/api/cms/writingstyle'
import { Post as OpenAI } from '@/api/cms/openai'
import { parseTime } from '@/utils'

const orderMapper = {
  'ascending': false,
  'descending': true,
  'null': ''
}

export default {
  name: 'WritingStyle',
  data() {
    return {
      title: '新增写作风格',
      dialogVisible: false,
      temp: {
        celebrity_name: '',
        style_description: '',
        remark: ''
      },
      rules: {
        celebrity_name: [
          { required: true, message: '请输入名人名字', trigger: 'blur' }
        ],
        style_description: [
          { required: true, message: '请输入风格描述', trigger: 'blur' }
        ]
      },
      kwInput: '',
      keyword: '',
      data: [],
      listLoading: false,
      action: '',
      orderby: 'create_at',
      orderdesc: true,
      selectedRows: [],
      // pagination
      pagesize: 20,
      page: 1,
      total: 0,
      // AI改写相关
      aiDialogVisible: false,
      aiTask: {
        originalContent: '',
        rewrittenContent: '',
        currentStyle: {
          celebrity_name: '',
          style_description: ''
        },
        loading: false
      },
      // 风格生成相关
      generatingStyle: false,
      styleExamples: [
        {
          name: 'Seth Godin',
          description: '请模仯Seth Godin的写作风格：使用简短有力的句子，每段不超过3-4句。采用直接、无修饰的商业化语言。多用反问句引发思考，以挑战性观点结束。用日常比喻解释复杂概念。避免冗长描述，每个词都要有价值。语调自信但不傲慢，启发式而非说教式。'
        },
        {
          name: '海明威',
          description: '请模仯海明威的写作风格：使用极简句式，避免形容词和副词。多用动词和名词，对话要精炼到极致。通过行动和细节暗示情感，不直接表达内心活动。采用冰山理论，表面简单内涵深刻。节奏紧凑，无废话。情感内敛克制，用简单词汇表达复杂感情。'
        },
        {
          name: '村上春树',
          description: '请模仯村上春树的写作风格：使用第一人称视角，营造亲近感。大量运用超现实比喻和奇特联想。在日常细节中融入哲学思考。语调平静淡然，略带忧郁色彩。善用重复和呼应手法。在现实与幻想间游走，创造迷幻氛围。用简单句式表达复杂情感。'
        },
        {
          name: 'Malcolm Gladwell',
          description: '请模仯Malcolm Gladwell的写作风格：以引人入胜的故事开头，用叙事引出观点。大量引用数据、研究和案例支撑论点。善于发现反直觉结论，挑战常识认知。使用通俗语言解释专业概念。结构清晰：故事-数据-结论。语调好奇而权威，让读者产生"原来如此"的感觉。'
        }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    parseTime,
    resetTemp() {
      this.temp = {
        celebrity_name: '',
        style_description: '',
        remark: ''
      }
    },
    getList() {
      this.listLoading = true
      const params = {
        page: this.page,
        pagesize: this.pagesize,
        kw: this.keyword,
        orderby: this.orderby,
        orderdesc: this.orderdesc
      }
      Get(params).then(response => {
        this.data = response.data.data
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleSearch() {
      this.keyword = this.kwInput
      this.page = 1
      this.getList()
    },
    handleSort(sort) {
      this.orderby = sort.prop || 'create_at'
      this.orderdesc = orderMapper[sort.order]
      this.getList()
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleSelectionChange(val) {
      this.selectedRows = val
    },
    handleAction(action, row) {
      this.action = action
      if (action === 'create') {
        this.title = '新增写作风格'
        this.resetTemp()
        this.dialogVisible = true
      } else if (action === 'edit') {
        this.title = '编辑写作风格'
        this.temp = {
          id: row.id,
          celebrity_name: row.celebrity_name,
          style_description: row.style_description,
          remark: row.remark
        }
        this.dialogVisible = true
      } else if (action === 'delete') {
        this.$confirm('确定要删除该写作风格吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          Delete(row.id).then(response => {
            this.$message({
              type: 'success',
              message: response.msg || '删除成功'
            })
            this.getList()
          })
        })
      }
    },
    handleAITask(row) {
      this.aiTask.currentStyle = {
        celebrity_name: row.celebrity_name,
        style_description: row.style_description
      }
      this.aiTask.originalContent = ''
      this.aiTask.rewrittenContent = ''
      this.aiTask.loading = false
      this.aiDialogVisible = true
    },
    async executeAIRewrite() {
      if (!this.aiTask.originalContent.trim()) {
        this.$message.warning('请输入需要改写的内容')
        return
      }

      this.aiTask.loading = true
      try {
        // 构建改写prompt
        const prompt = `请将以下内容改写成${this.aiTask.currentStyle.celebrity_name}的写作风格。

风格特点：${this.aiTask.currentStyle.style_description}

原始内容：
${this.aiTask.originalContent}

请用${this.aiTask.currentStyle.celebrity_name}的风格重新改写上述内容：`

        const response = await OpenAI({
          prompt: prompt,
          engine: 'gpt-4o-mini'
        })

        if (response.success) {
          // 提取文本内容（去除HTML标签）
          const tempDiv = document.createElement('div')
          tempDiv.innerHTML = response.content
          this.aiTask.rewrittenContent = tempDiv.textContent || tempDiv.innerText || ''
          this.$message.success('AI改写完成')
        } else {
          this.$message.error(response.msg || 'AI改写失败')
        }
      } catch (error) {
        console.error('AI改写失败:', error)
        this.$message.error('AI改写失败，请稍后重试')
      } finally {
        this.aiTask.loading = false
      }
    },
    onCelebrityNameBlur() {
      // 当用户输入名人名字后，可以自动提示生成风格
      if (this.temp.celebrity_name && !this.temp.style_description) {
        this.$message.info('您可以点击"AI生成风格描述"按钮自动生成专业的风格描述')
      }
    },
    async generateStyleDescription() {
      if (!this.temp.celebrity_name) {
        this.$message.warning('请先输入名人名字')
        return
      }

      this.generatingStyle = true
      try {
        const prompt = `请为"${this.temp.celebrity_name}"生成一个AI改写的风格要求prompt。

这个prompt是用来指导AI模仿该作者风格的，应该包含具体的写作指令。

要求：
1. 使用指令式语言，如"请使用..."、"采用..."、"注意..."
2. 包含具体的语言特点要求（如句式长短、用词特点）
3. 说明需要采用的修辞手法和表达方式
4. 指出该风格的情感基调和语气特征
5. 提及需要体现的思想深度或观点角度
6. 150-200字，要具体可操作

示例格式：
"请模仿[名人]的写作风格：[具体要求1]。[具体要求2]。在表达时[要求3]..."

请直接输出AI改写指令：`

        const response = await OpenAI({
          prompt: prompt,
          engine: 'gpt-4o-mini'
        })

        if (response.success) {
          // 提取纯文本
          const tempDiv = document.createElement('div')
          tempDiv.innerHTML = response.content
          this.temp.style_description = tempDiv.textContent || tempDiv.innerText || ''
          this.$message.success('风格描述生成成功')
        } else {
          this.$message.error(response.msg || '生成失败')
        }
      } catch (error) {
        console.error('生成风格描述失败:', error)
        this.$message.error('生成失败，请稍后重试')
      } finally {
        this.generatingStyle = false
      }
    },
    showStyleExamples() {
      const examples = this.styleExamples.map(e =>
        `<div style="margin-bottom: 15px;">
          <h4 style="color: #409EFF; margin: 5px 0;">${e.name}</h4>
          <p style="margin: 0; line-height: 1.6;">${e.description}</p>
        </div>`
      ).join('')

      this.$alert(
        `<div style="max-height: 400px; overflow-y: auto;">${examples}</div>`,
        '风格描述示例',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '我知道了',
          customClass: 'style-examples-dialog'
        }
      )
    },
    async optimizeStyleDescription() {
      if (!this.temp.style_description) {
        this.$message.warning('请先输入或生成风格描述')
        return
      }

      this.generatingStyle = true
      try {
        const prompt = `请优化以下AI改写指令，使其更加清晰、具体、易于AI理解和执行：

原始指令：
${this.temp.style_description}

优化要求：
1. 保持风格特点不变，但表述更清晰
2. 使用更具体的指令性语言
3. 添加必要的细节说明和示例
4. 确保AI能准确理解并执行
5. 结构化表达，条理清晰
6. 150-200字左右

请直接输出优化后的AI改写指令：`

        const response = await OpenAI({
          prompt: prompt,
          engine: 'gpt-4o-mini'
        })

        if (response.success) {
          const tempDiv = document.createElement('div')
          tempDiv.innerHTML = response.content
          this.temp.style_description = tempDiv.textContent || tempDiv.innerText || ''
          this.$message.success('风格描述优化成功')
        } else {
          this.$message.error(response.msg || '优化失败')
        }
      } catch (error) {
        console.error('优化风格描述失败:', error)
        this.$message.error('优化失败，请稍后重试')
      } finally {
        this.generatingStyle = false
      }
    },
    copyRewrittenContent() {
      if (!this.aiTask.rewrittenContent) {
        this.$message.warning('没有内容可复制')
        return
      }

      const textarea = document.createElement('textarea')
      textarea.value = this.aiTask.rewrittenContent
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      this.$message.success('已复制到剪贴板')
    },
    handleBatchDelete() {
      if (!this.selectedRows.length) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的记录'
        })
        return
      }
      this.$confirm(`确定要删除选中的 ${this.selectedRows.length} 条记录吗？`, '批量删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedRows.map(row => row.id)
        BatchDelete({ ids }).then(response => {
          this.$message({
            type: 'success',
            message: response.msg || '批量删除成功'
          })
          this.getList()
        })
      })
    },
    confirm() {
      if (this.action === 'delete') {
        return
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.action === 'create') {
            Post(this.temp).then(response => {
              this.$message({
                type: 'success',
                message: response.msg || '创建成功'
              })
              this.dialogVisible = false
              this.getList()
            })
          } else if (this.action === 'edit') {
            Put(this.temp.id, this.temp).then(response => {
              this.$message({
                type: 'success',
                message: response.msg || '更新成功'
              })
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ai-section {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .ai-section-title {
    margin: 0 0 15px 0;
    color: #303133;
    font-size: 16px;
    font-weight: bold;
  }

  .ai-section-footer {
    margin-top: 15px;
    text-align: center;
  }
}

.ai-style-info {
  margin-top: 20px;
  margin-bottom: 10px;
}

::v-deep .el-textarea__inner {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  line-height: 1.5;
}

.style-description-container {
  .style-helper-buttons {
    margin-top: 10px;
    display: flex;
    gap: 10px;
  }
}

::v-deep .style-examples-dialog {
  .el-message-box__message {
    padding: 10px 0;
  }
}
</style>

<style scoped>
.mt-pagination {
  margin-top: 20px;
}
</style>
